package vip.xiaonuo.visitor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import vip.xiaonuo.PushCallBack;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.param.MemberUserParam;
import vip.xiaonuo.facedoor.modular.message.SnowyMessageTemplate;
import vip.xiaonuo.facedoor.modular.message.Topic;
import vip.xiaonuo.facedoor.modular.message.domain.Message;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.mapper.VisitorMapper;
import vip.xiaonuo.facedoor.modular.visitor.param.VisitorParam;
import vip.xiaonuo.facedoor.modular.visitor.service.FacedoorVisitorService;
import vip.xiaonuo.modular.threemessagetable.entity.ThreeMessageTable;
import vip.xiaonuo.modular.threemessagetable.service.ThreeMessageTableService;
import vip.xiaonuo.sys.modular.file.enums.FileTypeEnum;
import vip.xiaonuo.sys.modular.file.service.SysFileInfoService;

import javax.annotation.Resource;
import java.util.List;


@Component
@RocketMQMessageListener(
        topic = Topic.FACE_DOOR_VISITOR_PUSH,                      // 1.topic：消息的发送者使用同一个topic
        consumerGroup = Topic.FACE_DOOR_VISITOR_PUSH,               // 2.group：不用和生产者group相同 ( 在RocketMQ中消费者和发送者组没有关系 )
        selectorExpression = "${tag}",                   // 3.tag：设置为 * 时，表示全部。
        messageModel = MessageModel.CLUSTERING    // 4.消费模式：默认 CLUSTERING （ CLUSTERING：负载均衡 ）（ BROADCASTING：广播机制 ）
)
public class VisitorListener implements RocketMQListener<MessageExt> {


    @Resource
    private FacedoorVisitorService visitorService;

    @Resource
    private VisitorMapper visitorMapper;

    @Resource
    private SnowyMessageTemplate snowyMessageTemplate;


    @Resource
    private SysFileInfoService sysFileInfoService;


    @Resource
    private ThreeMessageTableService threeMessageTableService;

    @Override
    public void onMessage(MessageExt messageExt) {
        PushCallBack pushCallBack = new PushCallBack();
        pushCallBack.setTenantCode(ConstantContextHolder.getRemoteTenantCode());
        pushCallBack.setDeptCode(ConstantContextHolder.getRemoteDeptCode());
        byte[] body = messageExt.getBody();
        String msg = new String(body);
        ThreeMessageTable threeMessageTable = new ThreeMessageTable();
        threeMessageTable.setTopic(Topic.FACE_DOOR_VISITOR_PUSH);
        threeMessageTable.setMsg(msg);
        threeMessageTableService.save(threeMessageTable);
        List<Visitor> visitors = JSON.parseArray(msg, Visitor.class);
        for (Visitor visitor : visitors) {
//            if (StringUtils.isBlank(visitor.getPhoto())) {
//                PushCallBack.Detail detail = new PushCallBack.Detail();
//                detail.setMessage("访客未上传图片");
//                detail.setId(visitor.getId());
//                detail.setName(visitor.getName());
//                pushCallBack.getFail().add(detail);
//                continue;
//            }
            try {
                // 图片上传
                String url = "";
                if (StringUtils.isNotBlank(visitor.getPhoto())){
                    url = sysFileInfoService.uploadFile(visitor.getPhoto(), FileTypeEnum.VISITOR);
                }
                Visitor dbVisitor = visitorMapper.selectById(visitor.getId());
                if (dbVisitor == null) {
                    VisitorParam visitorParam = new VisitorParam();
                    BeanUtil.copyProperties(visitor, visitorParam);
                    visitorParam.setOrgId(1265476890672672770L);
                    visitorParam.setPhoto(url);
                    visitorParam.setStatus(1);
                    visitorService.add(visitorParam);
                } else {
                    VisitorParam visitorParam = new VisitorParam();
                    BeanUtil.copyProperties(visitor, visitorParam);
                    visitorParam.setOrgId(1265476890672672770L);
                    visitorParam.setPhoto(url);
                    visitorParam.setStatus(1);
                    visitorService.edit(visitorParam);
                }
                PushCallBack.Detail detail = new PushCallBack.Detail();
                detail.setMessage("success");
                detail.setId(visitor.getId());
                detail.setName(visitor.getName());
                pushCallBack.getSuccess().add(detail);
            } catch (Exception e) {
                PushCallBack.Detail detail = new PushCallBack.Detail();
                detail.setMessage(ExceptionUtil.getMessage(e));
                detail.setId(visitor.getId());
                detail.setName(visitor.getName());
                pushCallBack.getFail().add(detail);
            }
        }
        Message message = new Message();
        message.setMsg(JSON.toJSONString(pushCallBack));
        message.setTopic(Topic.FACE_DOOR_VISITOR_CALL_BACK);
        snowyMessageTemplate.sendLocalTransactionalMessage(message);
        threeMessageTable.setReturnMsg(JSON.toJSONString(pushCallBack));
        threeMessageTableService.updateById(threeMessageTable);
    }
}


